<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>欢迎回来，{{ userStore.user?.full_name }}老师</h1>
      <p>今天是{{ currentDate }}，祝您工作愉快！</p>
    </div>

    <div class="dashboard-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#409EFF">
                <Document />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalExams }}</div>
                <div class="stat-label">总考试数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#67C23A">
                <Check />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.publishedExams }}</div>
                <div class="stat-label">已发布</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#E6A23C">
                <Clock />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.ongoingExams }}</div>
                <div class="stat-label">进行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#F56C6C">
                <Star />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalQuestions }}</div>
                <div class="stat-label">总题目数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>我的考试</span>
                <el-button type="primary" @click="$router.push('/exams')">
                  管理考试
                </el-button>
              </div>
            </template>
            <el-table :data="recentExams" style="width: 100%" v-loading="loading">
              <el-table-column prop="title" label="考试名称" />
              <el-table-column prop="start_time" label="开始时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.start_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="时长" width="100">
                <template #default="{ row }">
                  {{ row.duration }}分钟
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getExamStatusType(row)">
                    {{ getExamStatusText(row) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleEditExam(row)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="success" 
                    size="small"
                    @click="handleViewResults(row)"
                  >
                    成绩
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>快捷操作</span>
              </div>
            </template>
            <div class="quick-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="handleCreateExam"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><Plus /></el-icon>
                创建新考试
              </el-button>
              <el-button 
                type="success" 
                size="large" 
                @click="$router.push('/questions')"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><List /></el-icon>
                题库管理
              </el-button>
              <el-button 
                type="info" 
                size="large" 
                @click="$router.push('/scores')"
                style="width: 100%;"
              >
                <el-icon><DataLine /></el-icon>
                成绩分析
              </el-button>
            </div>
          </el-card>

          <el-card style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>待办事项</span>
              </div>
            </template>
            <div class="todo-list">
              <div 
                v-for="todo in todos" 
                :key="todo.id"
                class="todo-item"
              >
                <el-checkbox v-model="todo.completed">
                  {{ todo.text }}
                </el-checkbox>
                <div class="todo-date">{{ todo.date }}</div>
              </div>
              <el-empty v-if="todos.length === 0" description="暂无待办事项" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import api from '../api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Document, Check, Clock, Star, Plus, List, DataLine } from '@element-plus/icons-vue'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const exams = ref([])
const questions = ref([])

const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const stats = computed(() => {
  const totalExams = exams.value?.length || 0
  const publishedExams = exams.value?.filter(exam => exam.status === 'published').length || 0
  const ongoingExams = exams.value?.filter(exam => exam.status === 'ongoing').length || 0
  const totalQuestions = questions.value?.length || 0

  return {
    totalExams,
    publishedExams,
    ongoingExams,
    totalQuestions
  }
})

const recentExams = computed(() => {
  return exams.value?.slice(0, 5) || []
})

const todos = ref([
  { id: 1, text: '完成期末考试命题', date: '2024-01-15', completed: false },
  { id: 2, text: '批改月考试卷', date: '2024-01-10', completed: true },
  { id: 3, text: '更新题库', date: '2024-01-20', completed: false }
])

const loadData = async () => {
  loading.value = true
  try {
    const examsRes = await api.exams.getExams()
    exams.value = examsRes.data.items || examsRes.data
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN')
}

const getExamStatusType = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  if (now < startTime) return 'info'
  if (now > endTime) return 'danger'
  return 'success'
}

const getExamStatusText = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.start_time)
  const endTime = new Date(exam.end_time)
  
  if (now < startTime) return '未开始'
  if (now > endTime) return '已结束'
  return '进行中'
}

const handleCreateExam = () => {
  router.push('/exams')
}

const handleEditExam = (exam) => {
  router.push(`/exam/${exam.id}`)
}

const handleViewResults = (exam) => {
  router.push(`/scores?exam_id=${exam.id}`)
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.dashboard-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.dashboard-stats {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.todo-list {
  max-height: 300px;
  overflow-y: auto;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-date {
  font-size: 12px;
  color: #909399;
}
</style>